package com.example.demo.exception;

import com.port.fee.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLSyntaxErrorException;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<String> handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getDefaultMessage();
            }
        }
        return Result.validateFailed(message);
    }

    /**
     * 处理数据库异常
     */
    @ExceptionHandler(value = SQLSyntaxErrorException.class)
    public Result<String> handleSQLException(SQLSyntaxErrorException e) {
        LOGGER.error("数据库异常：", e);
        return Result.failed("数据库操作异常: " + e.getMessage());
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(value = RuntimeException.class)
    public Result<String> handleRuntimeException(RuntimeException e) {
        LOGGER.error("运行时异常：", e);
        return Result.failed("操作失败: " + e.getMessage());
    }

    /**
     * 处理未知异常
     */
    @ExceptionHandler(value = Exception.class)
    public Result<String> handleException(Exception e) {
        LOGGER.error("系统异常：", e);
        // 开发环境返回详细错误信息
        return Result.failed("系统异常：" + e.getClass().getName() + " - " + e.getMessage());
    }
}